const mdns = require('node-mdns');
//小程序的打印机
let printerIp = ''; // 当前连接的打印机 IP 地址
let browser = null; // mDNS 浏览器实例
let services = []; // 当前搜索到的打印机列表
let connected = false; // 当前是否已连接打印机
let connecting = false; // 当前是否正在连接打印机

// 连接打印机
async function connectPrinter(ip, data) {
	connecting = true;
	return new Promise((resolve, reject) => {
		uni.request({
			url: `http://${ip}/ipp/print`,
			method: 'POST',
			header: {
				'Content-Type': 'application/ipp'
			},
			data,
			success: (res) => {
				connecting = false;
				connected = true;
				printerIp = ip;
				resolve(res);
			},
			fail: (err) => {
				connecting = false;
				reject(err);
			}
		});
	});
}

// 断开打印机连接
function disconnectPrinter() {
	connected = false;
	printerIp = '';
}

// 搜索打印机
async function searchPrinters() {
	return new Promise((resolve, reject) => {
		browser = mdns.createBrowser(mdns.tcp('ipp'));

		browser.on('error', (err) => {
			reject(err);
		});

		const printers = [];

		browser.on('serviceUp', (service) => {
			// 解析打印机的 IP 地址
			const ip = service.addresses[0];

			// 获取打印机的名字和描述信息
			const name = service.txtRecord.name;
			const desc = service.txtRecord.desc;

			// 将打印机信息存入数组
			printers.push({
				name,
				ip,
				desc
			});
		});

		browser.on('serviceDown', (service) => {
			// 从当前搜索到的打印机列表中移除该打印机
			services = services.filter(s => s.ip !== service.addresses[0]);
		});

		browser.on('end', () => {
			services = printers;
			resolve(printers);
		});

		browser.start();
	});
}

// 停止搜索打印机
function stopSearch() {
	if (browser) {
		browser.stop();
	}
}

// 连接指定的打印机
function connectToPrinter(ip) {
	return new Promise((resolve, reject) => {
		if (connected) {
			// 已经连接了其他打印机，需要先断开连接
			disconnectPrinter();
		}
		// 连接指定的打印机
		const printData = {
			operation: 'printJob',
			version: '2.0',
			// ...
		};
		connectPrinter(ip, printData)
			.then(() => {
				// 连接成功，可以开始打印了
				resolve(ip)
			})
			.catch((err) => {
				console.error('连接打印机失败', err);
				reject()
			});
	});
}

// 用户选择完打印机后，会调用 connectToPrinter 方法连接该打印机，并开始打印。
// 打印文本
function printText(text, printerIp) {
	const printData = {
		operation: 'printJob',
		version: '2.0',
		'operation-attributes-tag': {
			'job-name': 'test.txt',
			'document-format': 'text/plain'
		},
		data: text
	};
	return connectPrinter(printerIp, printData);
}

// 打印图片
function printImage(imgUrl, printerIp) {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src: imgUrl,
			success: (info) => {
				uni.request({
					url: `http://${printerIp}/ipp/print`,
					method: 'POST',
					header: {
						'Content-Type': 'application/ipp'
					},
					data: {
						operation: 'printJob',
						version: '2.0',
						'operation-attributes-tag': {
							'job-name': 'test.png',
							'document-format': 'image/png'
						},
						data: uni.uploader.createUpload({
							url: `http://${printerIp}/ipp/print`,
							name: 'file',
							fileType: 'image',
							formData: {
								'job-name': 'test.png',
								'document-format': 'image/png'
							},
							filePath: imgUrl,
							success: () => {
								resolve();
							},
							fail: (err) => {
								reject(err);
							}
						}).start()
					},
					success: () => {
						resolve();
					},
					fail: (err) => {
						reject(err);
					}
				});
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}

async function printMain(type, data) {
	try {
		// 搜索打印机
		const printers = await searchPrinters();
		// 显示搜索到的打印机列表供用户选择
		const printerNames = printers.map(p => p.name);
		const res = await uni.showActionSheet({
			itemList: printerNames,
			itemColor: '#000000'
		});
		const selectedPrinter = printers[res.tapIndex];


		// 连接用户选择的打印机
		await connectToPrinter(selectedPrinter.ip);
		if (type == 'img') {
			printImage(data)
		} else if (type == 'text') {
			printText(data)
		}
	} catch (err) {
		console.error('搜索打印机失败', err);
	}
}

export {
	printMain
};